<template>
    <div id = "createsection">
         <h1>创建节</h1>
         <div class="title">
            <el-input v-model="section.title" placeholder="博客标题"></el-input>
            <el-input v-model="section.orderby" placeholder="权重"></el-input>
        </div>
            <div class="mavon-editor">
      <mavon-editor
        @change="updateDoc"
        @imgAdd="imgAdd"
        ref="editor"
        v-model="section.md_text"
      >
      </mavon-editor>
    </div>
    <div>
      <!-- 保存 -->
      <el-button type="success" class="title_titleb" @click="saveData"
        >保存</el-button
      >
    </div>
    </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import request from "../utils/request"
export default {
    data() {
        return {
        section: {
          title: "",
          orderby:"",
          md_text: "",
          html_text: "",
        },
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
    }
    },
    methods: {
         updateDoc(markdown, html) {
           // 此时会自动将 markdown 和 html 传递到这个方法中
           this.section.html_text = html;
         },
          saveData() {
          if (this.section.title) {
            request({
              method: "post",
              url: "section",
              data: {
                title: this.section.title,
                md_text: this.section.md_text,
                html_text: this.section.html_text,
                orderby: this.section.orderby,
                chapter_id: this.chapter_id
              },
            }).then((res) => {
              if(res.data.code === 20000){
                this.$message.success("添加成功")
                this.$router.push(`/section?chapter_id=${this.chapter_id}`);
              }else{
                this.$message.error("添加失败，请重试！")
              }
            });
          } else {
            this.$message.error("请输入标题");
          }
        },
         imgAdd(filename, $file) {
          let formdata = new FormData();
          formdata.append("image", $file);
          request({
            method: "post",
            url: `${process.env.VUE_APP_BASE_API}upload`,
            data: formdata,
            headers: { "Content-Tpye": "multipart/form-data" },
          }).then((res) => {
            let url = res.data.data.file;
            this.$refs.editor.$img2Url(filename, url);
          });
        },
         getUploadURL() {
           return `${process.env.VUE_APP_BASE_API}upload`;
         },
         handleRemove(file, fileList) {
           console.log(file, fileList);
         },
         handlePictureCardPreview(file) {
           this.dialogImageUrl = file.url;
           this.dialogVisible = true;
         },
    },
    components: {
        mavonEditor,
    },
    computed:{
      chapter_id(){
        return this.$route.query.chapter_id
      }
    },
}
</script>

<style lang="less">
    
</style>